package com.jcli.fx3u;

import com.jcli.HslCommunication.Core.Types.OperateResultExOne;
import com.jcli.HslCommunication.Profinet.Melsec.MelsecA1ENet;

import java.util.Date;

/**
 * 演示从PLC中读取D寄存器的数据
 * 优化了代码结构，并添加了注释
 *
 * @author ljc
 * @version 1.0
 * @date 2023/11/10 20:44
 */
public class _1114_PLCDataReaderDemo {

    public static void main(String[] args) {
        // 创建Melsec A1E客户端对象并与PLC通信
        MelsecA1ENet melsecNet = new MelsecA1ENet("192.168.1.11", 3000);
        melsecNet.SetPersistentConnection();
        System.out.println("连接成功");

        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 读取多个D寄存器的数据
        readAndPrintData(melsecNet, "D1");
        readAndPrintData(melsecNet, "D31");
        readAndPrintData(melsecNet, "D61");
        readAndPrintData(melsecNet, "D91");
        readAndPrintData(melsecNet, "D121");
        readAndPrintData(melsecNet, "D151");
        readAndPrintData(melsecNet, "D181");
        readAndPrintData(melsecNet, "D211");

        // 记录结束时间
        long endTime = System.currentTimeMillis();
        System.out.println("读取耗时：" + (endTime - startTime) + "ms");
    }

    /**
     * 读取并打印PLC的D寄存器数据
     *
     * @param melsecNet    MelsecA1ENet对象
     * @param startAddress 起始寄存器地址
     */
    private static void readAndPrintData(MelsecA1ENet melsecNet, String startAddress) {

        // 获取当前时间
        Date date = new Date();
        System.out.println(date.toString());

        // 读取D寄存器的数据
        OperateResultExOne<int[]> readResult = melsecNet.ReadInt32(startAddress, (short) 30);

        // 打印读取结果
        if (readResult.IsSuccess) {
            printIntArray(readResult.Content);
        } else {
            System.out.println("读取失败");
        }

        System.out.println();
    }

    /**
     * 打印int数组的值
     *
     * @param data int数组
     */
    private static void printIntArray(int[] data) {
        for (int value : data) {
            System.out.print(value + " ");
        }
    }
}
